package com.qcby.xmdemo.tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class DistributedLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "return redis.call('del', KEYS[1]) " +
            "else return 0 end";

    public boolean tryLock(String key, String value, long expireTime, TimeUnit unit) {
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, unit);
        return Boolean.TRUE.equals(success);
    }

    public boolean releaseLock(String key, String value) {
        RedisScript<Long> redisScript = RedisScript.of(LOCK_SCRIPT, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        return result != null && result > 0;
    }
}
